package com.zyh.alpacaDemo.account;


/**
 * @Classname AlpacaAccountService
 * @Description TODO()
 * @Date 2025-09-01 20:22
 * @Created by 86177
 */
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.Base64;

public class AlpacaAccountService {

    // 1. 定义常量（你的API凭证和基础URL）
    // !!重要!! 实际开发中应从环境变量或安全配置中读取，不要硬编码！
    private static final String API_KEY_ID = "CK12643YAM8UFHA6L62I";
    private static final String API_SECRET_KEY = "geWlg29V86nGODx8105u8u1kcefbW7Hy2tGCeHaP";
    private static final String BASE_URL = "https://broker-api.sandbox.alpaca.markets";

    // 2. 创建全局的OkHttpClient和ObjectMapper实例，它们线程安全，可重复使用。
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static void main(String[] args) {
        String accountId = "85fae14c-0f3c-4789-b8c8-37af34128cec"; // 要查询的账户ID

        try {
            // 3. 调用方法获取账户信息（JSON字符串格式）
            String accountJson = getAccountById(accountId);
            System.out.println("RAW JSON RESPONSE:");
            System.out.println(accountJson);

            System.out.println("===============================");
            // 4. （可选但推荐）将JSON字符串转换为Java对象
            // 你需要先根据Alpaca API返回的字段结构创建一个Account类
             Account account = OBJECT_MAPPER.readValue(accountJson, Account.class);
             System.out.println("Parsed Account ID: " + account.getId());

        } catch (IOException e) {
            System.err.println("An error occurred during the HTTP request: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("An unexpected error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static String getAccountById(String accountId) throws IOException {
        // 1. 构建请求URL
        HttpUrl url = HttpUrl.parse(BASE_URL).newBuilder()
                .addPathSegment("v1")
                .addPathSegment("accounts")
                .addPathSegment(accountId)
                .build();

        // 2. 构建Basic Auth认证头
        String credentials = API_KEY_ID + ":" + API_SECRET_KEY;
        String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());

        // 3. 构建请求对象
        Request request = new Request.Builder()
                .url(url)
                .get() // 指定GET方法
                .addHeader("accept", "application/json")
                .addHeader("authorization", authHeaderValue)
                .build();

        // 4. 使用OkHttpClient发送同步请求并获取响应
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {

            // 5. 检查请求是否成功 (HTTP code 200)
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response + ". Body: " + (response.body() != null ? response.body().string() : "null"));
            }

            // 6. 从响应体中提取字符串（JSON格式）
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.string();
            } else {
                throw new IOException("Response body is null.");
            }
        }
    }
}
